package cn.jinjimi.app.util;

import cn.jinjimi.base.preference.PreferenceManager;
import cn.jinjimi.base.util.LimitQueue;
import cn.jinjimi.base.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by lingyiyong on 17/9/27.
 */

public class SearchRecordManager {
    private LimitQueue<String> historyQueue;

    private int limit;

    private String saveKey;

    public SearchRecordManager(String saveKey, int limit) {
        this.saveKey = saveKey;
        this.limit = limit;
        init();
    }

    private void init() {
        historyQueue = new LimitQueue<>(limit);
    }

    public List<String> getRecords() {
        String strCache = PreferenceManager.getStringData(saveKey);
        List<String> strings = new ArrayList<>();
        if (StringUtils.isNotEmpty(strCache)) {
            for (String str : Arrays.asList(strCache.split(","))) {
                if (historyQueue.contains(str))
                    historyQueue.remove(str);

                historyQueue.offer(str);
                strings.add(str);
            }
        }
        return strings;
    }

    public void addRecord(String keyWord) {
        if (historyQueue.contains(keyWord))
            historyQueue.remove(keyWord);

        historyQueue.offer(keyWord);

        StringBuilder stringBuilder = new StringBuilder();
        for (String str : historyQueue) {
            stringBuilder.append(str).append(",");
        }

        if (stringBuilder.length() > 0)
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);

        PreferenceManager.setData(saveKey, stringBuilder.toString());
    }

    public void clearRecords() {
        historyQueue.clear();
        PreferenceManager.setData(saveKey, "");
    }

    public int size() {
        return historyQueue.size();
    }

    public String peek() {
        return historyQueue.peek();
    }
}
